package org.chnxi.study.datastructrues.stack;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 使用单向链表模拟栈
 * @param <E>
 */
public class ListStack<E> {

    private Node<E> head;

    private int size;

    public ListStack(){
        head = new Node<E>();
        size = 0;
    }

    public boolean isEmpty(){
        return head.next == null;
    }

    /**
     * 直接向链表头部插入数据
     * @param e
     */
    public void push(E e){
        Node<E> node = new Node<>(e);
        if(head.getNext() != null){
            node.setNext(head.getNext());
        }
        head.setNext(node);
        size++;
    }

    /**
     * 直接从链表头部取出数据
     * @return
     */
    public E pop(){
        if(size < 1){
            System.out.println("栈空了");
            return null;
        }
        Node node = head.getNext();
        head.setNext(node.getNext());
        size--;
        return (E)node.getE();
    }

    public E peek(){
        if(size < 1){
            System.out.println("栈空了");
            return  null;
        }
        return head.getNext().getE();
    }

    /**
     * 从头部遍历链表数据进行输出
     */
    public void print(){
        if(head.getNext() == null){
            System.out.println("栈是空的");
        }

        Node<E> tmp = head.next;

        while (true){
            if(tmp == null){
                break;
            }
            System.out.println("栈元素："+tmp.getE());
            tmp = tmp.next;
        }

    }

}

@Data
@NoArgsConstructor
@AllArgsConstructor
class Node<E>{
    E e;
    Node<E> next;

    Node(E e){
        this.e = e;
    }
}
